//
// Tokaplot
// https://code.google.com/p/tokaplot/
//
// License: GPL v3
// https://code.google.com/p/tokaplot/wiki/License
//
// This file is part of Tokaplot.
//
// Tokaplot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Tokaplot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Tokaplot. If not, see <http://www.gnu.org/licenses/>
//

package com.tokaplot;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.CheckBox;

public class ConfigPlot extends Activity {

    private WidgetInfo wInfo = null;
    private boolean useSensors = false;

    CharSequence[] plotItems = null;

    private long syncRateDefault = 60000;
    private long syncRate = syncRateDefault;
    private long rateWarning = 60000;

    public ConfigPlot() {
        super();
    }
    
    // Time picker
    private int tSelected = 0;
    private DialogTime.timeDoneListener timeDialogListener =
        new DialogTime.timeDoneListener() {
            public void done(long time) {
                
                // Create readable string from milliseconds
                String tText = timeText(time);
                
                switch(tSelected) {
                case 1:
                    ((Button) findViewById(R.id.pconfig_button_plot_sample)).setText(tText);
                    wInfo.setSampRate(time);
                    break;
                case 2:
                    ((Button) findViewById(R.id.pconfig_button_plot_log)).setText(tText);
                    syncRate = time;
                    break;
            }
            }
            
    };
    
    // Warning messages
    private final static String warningText_Sensors = "Using sensors may decrease battery life.";
    private final static String warningText_Sample = "Low sample rates may decrease battery life.";
    private final static String warningText_Both = "Using sensors and low sample rates will decrease battery life.";

    protected void onActivityResult(int requestCode, int resultCode, Intent i) {

        if (wInfo != null && resultCode == RESULT_OK) {

            // Get passed style from intent
            int style = 0;
            int col = 0;
            Bundle extras = i.getExtras();
            if (extras != null) {
                style = extras.getInt(LinePicker.EXTRA_LINESTYLE, 0);
                col = extras.getInt(LinePicker.EXTRA_LINECOLOUR, 0);
            }

            switch (requestCode) {
            case 1:
                wInfo.setStyle1(style);
                wInfo.setCol1(col);
                break;

            case 2:
                wInfo.setStyle2(style);
                wInfo.setCol2(col);
                break;
            }
        }
    }

    // Dialogs
    private final int DIALOG_PLOT_1 = 2;
    private final int DIALOG_PLOT_2 = 3;

    protected void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {
        case DIALOG_PLOT_1:
            break;
        case DIALOG_PLOT_2:
            break;
        }
    }

    protected Dialog onCreateDialog(int id) {

        int i = 0;
        Dialog dialog = null;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        switch (id) {

        case DIALOG_PLOT_1:
            builder.setTitle("Select plot 1 type");

            // Find selected item
            for (CharSequence s : plotItems) {
                if (s.toString().equals(wInfo.getType1()))
                    break;
                i++;
            }
            builder.setSingleChoiceItems(plotItems, i, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) {
                    wInfo.setType1(plotItems[item].toString());
                    ((Button) findViewById(R.id.pconfig_button_plot1_type)).setText(wInfo.getType1());
                    dialog.dismiss();
                }
            });
            dialog = builder.create();
            break;

        case DIALOG_PLOT_2:
            builder.setTitle("Select plot 2 type");

            // Find selected item
            for (CharSequence s : plotItems) {
                if (s.toString().equals(wInfo.getType2()))
                    break;
                i++;
            }
            builder.setSingleChoiceItems(plotItems, i, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) {
                    wInfo.setType2(plotItems[item].toString());
                    ((Button) findViewById(R.id.pconfig_button_plot2_type)).setText(wInfo.getType2());
                    dialog.dismiss();
                }
            });
            dialog = builder.create();
            break;

        default:
            dialog = null;
            break;
        }

        // Set warnings
        if (TokaplotService.isDeviceSensor(wInfo.getType1()) || TokaplotService.isDeviceSensor(wInfo.getType2())) {
            useSensors = true;
            if (wInfo.getSampRate() < rateWarning || syncRate < rateWarning)
                ((TextView) findViewById(R.id.pconfig_text_warning)).setText(warningText_Both);
            else
                ((TextView) findViewById(R.id.pconfig_text_warning)).setText(warningText_Sensors);
        } else {
            useSensors = false;
            if (wInfo.getSampRate() < rateWarning || syncRate < rateWarning)
                ((TextView) findViewById(R.id.pconfig_text_warning)).setText(warningText_Sample);
            else
                ((TextView) findViewById(R.id.pconfig_text_warning)).setText("");
        }

        return dialog;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setResult(RESULT_CANCELED);
        
        // Find widget id
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            wInfo = new WidgetInfo(intent);
        }
        if (wInfo.getID() == AppWidgetManager.INVALID_APPWIDGET_ID)
            finish();

        if (TokaplotService.isDeviceSensor(wInfo.getType1()) || TokaplotService.isDeviceSensor(wInfo.getType2())) {
            useSensors = true;
        } else {
            useSensors = false;
        }

        // Get sync rate
        SharedPreferences mPrefs = getSharedPreferences("TP", Context.MODE_PRIVATE);
        syncRate = mPrefs.getLong("sync_Rate", syncRateDefault);

        // Get list of sensors
        plotItems = TokaplotService.getSensorStrings();

        //  Setup view
        setContentView(R.layout.config_plot);        
        
        ((Button) findViewById(R.id.pconfig_button_plot_sample)).setText(timeText(wInfo.getSampRate()));
        findViewById(R.id.pconfig_button_plot_sample).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                tSelected = 1;
                new DialogTime(ConfigPlot.this, wInfo.getSampRate(), timeDialogListener).show();
            }
        });        

        ((Button) findViewById(R.id.pconfig_button_plot_log)).setText(timeText(syncRate));
        findViewById(R.id.pconfig_button_plot_log).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                tSelected = 2;
                new DialogTime(ConfigPlot.this, syncRate, timeDialogListener).show();
            }
        });

        ((Button) findViewById(R.id.pconfig_button_plot1_type)).setText(wInfo.getType1());
        findViewById(R.id.pconfig_button_plot1_type).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DIALOG_PLOT_1);
            }
        });

        ((Button) findViewById(R.id.pconfig_button_plot2_type)).setText(wInfo.getType2());
        findViewById(R.id.pconfig_button_plot2_type).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DIALOG_PLOT_2);
            }
        });

        findViewById(R.id.pconfig_button_plot1_sty).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent i = new Intent(ConfigPlot.this, LinePicker.class);
                i.putExtra(LinePicker.EXTRA_LINESTYLE, wInfo.getStyle1());
                i.putExtra(LinePicker.EXTRA_LINECOLOUR, wInfo.getCol1());
                startActivityForResult(i, 1);
            }
        });

        findViewById(R.id.pconfig_button_plot2_sty).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent i = new Intent(ConfigPlot.this, LinePicker.class);
                i.putExtra(LinePicker.EXTRA_LINESTYLE, wInfo.getStyle2());
                i.putExtra(LinePicker.EXTRA_LINECOLOUR, wInfo.getCol2());
                startActivityForResult(i, 2);
            }
        });

        if (wInfo.getShowText1()) {
            ((CheckBox) findViewById(R.id.pconfig_check_text1)).setChecked(true);
        } else {
            ((CheckBox) findViewById(R.id.pconfig_check_text1)).setChecked(false);
        }
        if (wInfo.getShowText2()) {
            ((CheckBox) findViewById(R.id.pconfig_check_text2)).setChecked(true);
        } else {
            ((CheckBox) findViewById(R.id.pconfig_check_text2)).setChecked(false);
        }

        // Set warnings
        if ((wInfo.getSampRate() < rateWarning || syncRate < rateWarning) && useSensors == true)
            ((TextView) findViewById(R.id.pconfig_text_warning)).setText(warningText_Both);
        else if (useSensors == true)
            ((TextView) findViewById(R.id.pconfig_text_warning)).setText(warningText_Sensors);
        else if (wInfo.getSampRate() < rateWarning || syncRate < rateWarning)
            ((TextView) findViewById(R.id.pconfig_text_warning)).setText(warningText_Sample);
        else
            ((TextView) findViewById(R.id.pconfig_text_warning)).setText("");

        //  Listeners        
        findViewById(R.id.pconfig_button_done).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                // Get checks
                if (((CheckBox) findViewById(R.id.pconfig_check_text1)).isChecked() == true)
                    wInfo.setShowText1();
                else
                    wInfo.unsetShowText1();

                if (((CheckBox) findViewById(R.id.pconfig_check_text2)).isChecked() == true)
                    wInfo.setShowText2();
                else
                    wInfo.unsetShowText2();

                // Pass back to widget
                Intent resultValue = new Intent();
                resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, wInfo.getID());
                setResult(RESULT_OK, resultValue);

                // Save log rate
                SharedPreferences mPrefs = getSharedPreferences("TP", Context.MODE_PRIVATE);
                SharedPreferences.Editor ed = mPrefs.edit();
                ed.putLong("sync_Rate", syncRate);
                ed.commit();

                // Return options
                Intent widgetIntent = new Intent();
                widgetIntent.setAction(TokaplotService.ACTION_APPWIDGET_CONFIG);

                wInfo.setIntentWithInfo(widgetIntent);
                sendBroadcast(widgetIntent);

                finish();
            }
        });

        findViewById(R.id.pconfig_button_cancel).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                // Pass back to widget
                setResult(RESULT_CANCELED);

                finish();
            }
        });
    }
    
    public String timeText(long tMilli) {
        
        long ttime = tMilli/1000;
        long tsec = ttime%60;
        long tmin = (ttime%3600)/60;
        long thrs = (ttime%86400)/3600;
        long tdays = ttime/86400;
        String infoText = "";
        if (tdays!=0)
            infoText = infoText + tdays + " d ";
        if (thrs!=0)
            infoText = infoText + thrs + " h ";
        if (tmin!=0)
            infoText = infoText + tmin + " m ";
        if (tsec!=0)
            infoText = infoText + tsec + " s ";
        return infoText;
    }    
}
